package com.qibo.baselib.base;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * adapter 继承 FragmentPagerAdapter/FragmentStatePagerAdapter时setUserVisibleHint 才会调用,这个时候LazyLoadFragment 才会起作用；
 */
public abstract class LazyLoadFragment extends Fragment
{
    private static final String TAG = "LazyLoadFragment";
    private View mView;
    private boolean mIsLoaded = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        mIsLoaded = false;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        if (mView == null)
        {
            mView = inflater.inflate(getContentViewId(),container,false);
        }
        initBeforeStart();

        initView(mView);
        initAction();
        return mView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
    {
        synchronized (TAG)
        {
            if (!mIsLoaded)
            {
                if (getUserVisibleHint())
                {
                    lazyLoad();
                    mIsLoaded = true;
                }
            }
        }

        super.onViewCreated(view, savedInstanceState);
    }

    protected void initBeforeStart()
    {

    }

    protected abstract int getContentViewId();

    protected abstract void initView(View view);

    protected abstract void initAction();

    protected abstract void lazyLoad();

    protected View getCurrentView()
    {
        return mView;
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser)
    {
        super.setUserVisibleHint(isVisibleToUser);
        if (mView == null){
            return;
        }
        synchronized (TAG)
        {
            if (isVisibleToUser)
            {
                if (isRefreshDateEveryTimeIn())
                {
                    mIsLoaded = false;
                }
                if (!mIsLoaded)
                {
                    lazyLoad();
                    mIsLoaded = true;
                }
            }
        }
    }

    public boolean isRefreshDateEveryTimeIn()
    {
        return false;
    }

    @Override
    public void onDestroyView()
    {
        mIsLoaded = false;
        mView = null;
        super.onDestroyView();
    }
}
